import numpy as np
import matplotlib.pyplot as plt
from python_ai.common.xcommon import sep

from sklearn.metrics import homogeneity_score, completeness_score, v_measure_score


def x_my_metrics():
    """
    https://sklearn.apachecn.org/docs/master/22.html
    2.3.10.3. 同质性，完整性和 V-measure

    :return:
    """
    global h
    h = np.array(h)
    pm = homogeneity_score(y, h)
    r = completeness_score(y, h)
    vm = v_measure_score(y, h)
    print(f'同质性（均一性）： {pm}')
    print(f'完整性： {r}')
    print(f'V-measure： {vm}')


plt.figure(figsize=[8, 8])
spr = 2
spc = 2
spn = 0

# data 1
from sklearn.datasets import make_blobs, make_circles
x1, y1 = make_circles(n_samples=5000, factor=0.6, noise=0.05, random_state=9)
x2, y2 = make_blobs(n_samples=1000, n_features=2, centers=[[1.2,1.2]],
                   cluster_std=[[.1]],
                   random_state=9,
                   )
base = max(np.unique(y1)) + 1
y2 += base
x = np.r_[x1, x2]
y = np.r_[y1, y2]
spn += 1
plt.subplot(spr, spc, spn)
plt.title('data')
plt.scatter(x[:, 0], x[:, 1], s=1)

# layer-cluster agg for data 1
title = 'layer-cluster agg for data 1'
sep(title)
k = 3
from sklearn.cluster import AgglomerativeClustering
model = AgglomerativeClustering(n_clusters=k)
h = model.fit_predict(x)
x_my_metrics()
spn += 1
plt.subplot(spr, spc, spn)
plt.title(title)
cmap = plt.cm.get_cmap('rainbow', k)
for i in range(k):
    idx = h == i
    plt.scatter(x[idx, 0], x[idx, 1], s=1, color=cmap(i), label=f'class#{i+1}')
plt.legend()

# data 2
data = np.loadtxt(r'../../../ML/clustering/data/test.txt')

from sklearn.preprocessing import StandardScaler
data = StandardScaler().fit_transform(data)
x = data
spn += 1
plt.subplot(spr, spc, spn)
plt.title('data')
plt.scatter(x[:, 0], x[:, 1], s=1)

# layer-cluster agg for data 2
title = 'layer-cluster agg for data 2'
sep(title)
k = 4
from sklearn.cluster import AgglomerativeClustering
model = AgglomerativeClustering(n_clusters=k)
h = model.fit_predict(x)
from sklearn.metrics import silhouette_score
ss = silhouette_score(x, h)
print(f'Silhouette score: {ss}')
# x_my_metrics()  # Cannot do this, no label at beginning.
spn += 1
plt.subplot(spr, spc, spn)
plt.title(title)
cmap = plt.cm.get_cmap('rainbow', k)
for i in range(k):
    idx = h == i
    plt.scatter(x[idx, 0], x[idx, 1], s=1, color=cmap(i), label=f'class#{i+1}')
plt.legend()

# Finally show all plotting
plt.show()
